#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    int fd[1024] = {0};
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);//创建socket ipv4协议 流式套接字 具体的协议类型
    if (-1 == sockfd) { perror("socket"); exit(1); }

    int opt = 1;
    setsockopt(sockfd,SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));   //地址可以被重复绑定

    struct sockaddr_in server_addr;    //保存服务器的信息
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8000);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  //127.0.0.1回环ip 表示本机 测试时候可以用

    int ret = bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); //绑定信息
    if (-1 == ret) { perror("bind"); exit(1); }

    ret = listen(sockfd, 10); //设置监听队列
    if (-1 == ret) { perror("listen"); exit(1); }

    fd_set readfd, tmpfd;         //定义集合
    FD_ZERO(&readfd);             //清空集合
    FD_SET(sockfd, &readfd);      //添加到集合
    int maxfd = sockfd, i = 0;
    struct sockaddr_in client_addr;   //用于保存客户端的信息
    socklen_t length = sizeof(client_addr);
    char buf[32] = {0};

    while(1){ //循环服务器
        tmpfd = readfd;
        ret = select(maxfd + 1, &tmpfd, NULL, NULL, NULL); //监听集合是否可读 timeout NULL表示阻塞
        if (-1 == ret) { perror("select"); exit(1); } //出错就退出
        //没有出错表示有文件描述符可读
        if(FD_ISSET(sockfd, &tmpfd)){ //判断sockfd是否还留在集合里面  判断是否有客户端发起连接
            for (i = 0; i < 1024; i++) { if (fd[i] == 0) { break; } } //选择合适的i
            fd[i] = accept(sockfd, (struct sockaddr *)&client_addr, &length);
            if (-1 == fd[i]) { perror("accept"); exit(1); }

            printf("接受来自%s的客户端的连接 fd = %d\n", inet_ntoa(client_addr.sin_addr), fd[i]);

            FD_SET(fd[i], &readfd);       //新的文件描述符加入到集合中
            if (maxfd < fd[i]) { maxfd = fd[i]; }
        }
        else{ //有客户端发消息过来
            for (i = 0; i < 1024; i++) {
                if(FD_ISSET(fd[i], &tmpfd)){    //判断是哪个fd可读
                    ret = recv(fd[i], buf, sizeof(buf), 0);
                    if (-1 == ret) { perror("recv"); }
                    else if (0 == ret) {
                        close(fd[i]);    //关闭TCP连接
                        FD_CLR(fd[i], &readfd);    //从集合中清除掉
                        printf("客户端%d下线!\n", fd[i]);
                        fd[i] = 0;
                    }
                    else { printf("收到%d客户端的消息%s\n", fd[i], buf); }
                    memset(buf, 0, sizeof(buf));
                    break;
                }
            }
        }
    }
    return 0;
}
